package cn.edu.scnu.user.service;

import cn.edu.scnu.pojo.PersonalUser;
import cn.edu.scnu.pojo.User;
import cn.edu.scnu.pojo.UserInfo;
import cn.edu.scnu.user.mapper.OrgMapper;
import cn.edu.scnu.user.mapper.UserMapper;
import cn.edu.scnu.utils.MD5Util;
import cn.edu.scnu.utils.MapperUtil;
import cn.edu.scnu.vo.Card;
import cn.edu.scnu.vo.PersonalUserVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import redis.clients.jedis.JedisCluster;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrgMapper orgMapper;

    @Autowired
    private JedisCluster jedis;

    public User checkUsername(String username) {
        return userMapper.checkUsername(username);
    }

    @Transactional(rollbackFor = Exception.class)
    public void registerUser(User user) {
        user.setId(UUID.randomUUID().toString());
        user.setPassword(MD5Util.md5(user.getPassword()));
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        String table = null;
        try {
            if (user.getType() == 1) {
                orgMapper.registerOrgInfo(userInfo);
            } else {
                user.setType(2);
                userMapper.registerUserInfo(userInfo);
            }
            userMapper.registerUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException("注册失败");
        }
    }

    public void saveUser(PersonalUser user) {
        userMapper.saveUser(user);
    }

    public PersonalUserVO getUserByUname(String username) {
        PersonalUserVO personalUserVO = userMapper.getUserByUname(username);
        if (personalUserVO != null) {
            Map<String, String> info = userMapper.getInfoByUsername(username);
            personalUserVO.setNickname(info.get("nickname"));
            personalUserVO.setImgurl(info.get("imgurl"));
            return personalUserVO;
        }
        return null;
    }

    public String doLogin(User user) {
        user.setPassword(MD5Util.md5(user.getPassword()));
        User exist = userMapper.queryUserNameAndPassword(user);
//        Object userInfo = exist;
        if (exist == null) {
            System.out.println("---------------------1--------------------");
            return "";
        } else {
            System.out.println("---------------------2--------------------");
            String ticket = UUID.randomUUID().toString();
            String userJson;
            try {
//                if (user.getType() == 1) {
//                    userInfo = orgMapper.getOrgByUname(exist.getUsername());
//                } else if (user.getType() == 2) {
//                    userInfo = userMapper.getUserByUname(exist.getUsername());
//                }
//                userJson = MapperUtil.MP.writeValueAsString(userInfo);
                userJson = MapperUtil.MP.writeValueAsString(exist);
                // 登录顶替
                String existTicket = jedis.get("user_logined_" + exist.getId());
                if (StringUtils.isNotEmpty(existTicket)) {
                    jedis.del(existTicket);
                }
                // 定义当前客户端登录的信息user_logined_userId:ticket
                jedis.setex("user_logined_" + exist.getId(), 60 * 30, ticket);
                jedis.setex(ticket, 60 * 30, userJson);
                return ticket;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
    }

    public String queryUserJson(String ticket) {
        try {
            String userJson = "";
            long leftTime = jedis.pttl(ticket);
            userJson = jedis.get(ticket);
            if (leftTime < 1000 * 60 * 10) {
                jedis.pexpire(ticket, leftTime + 1000 * 60 * 5);
                User user = MapperUtil.MP.readValue(userJson, User.class);
                jedis.pexpire("user_logined_" + user.getId(), leftTime + 1000 * 60 * 5);
            }
            return userJson;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public void doLogout(User user) {
        String existTicket = jedis.get("user_logined_" + user.getId());
        jedis.del(existTicket);
        jedis.del("user_logined_" + user.getId());
    }

    public void updateImg(String username, String url) {

        userMapper.updateImg(username, url);
        // TODO 存在高并发问题 待优化
        String key = username + ":info";
        if (jedis.exists(key)) {
            jedis.hset(key, "imgurl", url);
        }
    }

    public void updateNick(String username, String nickname) {
        userMapper.updateNick(username, nickname);
        // TODO 存在高并发问题 带优化
        String key = username + ":info";
        if (jedis.exists(key)) {
            jedis.hset(key, "nickname", nickname);
        }
    }

    public Map<String, String> getInfoByUsername(String username) {
        // TODO 可加锁优化
        String key = username + ":info";
        Map<String, String> result = null;
        if (jedis.exists(key)) {
            result = jedis.hgetAll(key);
        } else {
            result = userMapper.getInfoByUsername(username);
            for (String k : result.keySet()) {
                jedis.hset(key, k, result.get(k));
            }
            jedis.expire(key, 60 * 60 * 24);
        }
        return result;

    }

    public List<Card> searchUsersByNickname(String nickname) {
        return userMapper.searchUsersByNickname(nickname);
    }
}
